import React, {ChangeEvent, useEffect, useState} from 'react';
import {Input} from "antd";
import {useLocation, useNavigate, useSearchParams} from "react-router-dom";
import {LIST_SEARCH_PARAMS_KEY} from "../constants";

const {Search} = Input;

const ListSearch: React.FC = () => {
  const [value, setValue] = useState<string>('')
  const nav = useNavigate()
  const {pathname} = useLocation()

  function handleSearch(value: string) {
    console.log('search', value, pathname)
    nav({
      pathname,
      search: `${LIST_SEARCH_PARAMS_KEY}=${value}`
    })
  }

  // 获取params参数 并设置到input
  const [searchParams] = useSearchParams()
  useEffect(() => {
    const curVal = searchParams.get(LIST_SEARCH_PARAMS_KEY) || ''
    setValue(curVal)
  }, [searchParams]);


  function handleOnchange(event: ChangeEvent<HTMLInputElement>) {
    setValue(event.target.value)
  }

  return (
    <div>
      <Search value={value} placeholder="请输入关键字"
              allowClear
              onSearch={handleSearch}
              onChange={handleOnchange}
              style={{width: 200}}/>
    </div>
  );
};

export default ListSearch;
